﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DBLayer;

namespace EngineLayer
{
    using EngineLayer.Services;
    using EngineLayer.Properties;
    using EngineLayer.Model;
      
    public class LoginModel : DBEntities
    {   
        private string _Name;
        private string _Description;
        private int _TotalRights;
        private Int32 _ID;

        private int intLoginAttempts;
        private bool userIsValid = false;
        private const string SYS_ADMIN = "sysadmin";


        public  LoginModel()
        {
            if (database.SystemUsers.Count() == 0)
            {
                database.SystemUsers.AddObject(new SystemUser
                                  { 
                                    LoginID = SYS_ADMIN,
                                    Name = SYS_ADMIN,
                                    Description = SYS_ADMIN,
                                    Password = SYS_ADMIN,
                                    Rights = (Int16)ItemRights.FullAccess
                                  });
                
                
                SaveChanges();
            }
        }
      
        public bool Validate(string loginID, string password)
        {
            intLoginAttempts += 1;
            SystemUser findUser = database.SystemUsers.Where(h => h.LoginID == loginID && h.Password == password).SingleOrDefault();
            if (findUser != null)
            {
                findUser.Logins++;
                this.userIsValid = true;
                this._ID = findUser.Id;
                this._Description = findUser.Description;
                this._Name = findUser.Name;
                this._TotalRights = findUser.Rights;
                SaveChanges();
                throw new Exception(EngineResources.Sucess);
            }
            else
            {
                if (intLoginAttempts >= 3)
                {
                    throw new Exception(EngineResources.Invalid);
                }
            }
            return false;
        }

        public Boolean Valid()
        {
            return userIsValid;
        }
  
        public string Name 
        { 
            get { return this._Name; } 
        }

        public string Description 
        {
            get { return this._Description; } 
        }

        public int TotalRights 
        { 
            get { return this._TotalRights; } 
        }

        public int ID 
        { 
            get { return this._ID ; }
        }
 
     
    }

    }

